#!/bin/python
#
# Convert Marker model objects in to a XML/KML format
#
# Will Cooke
# 2009

#Just a comment:
example_format = """

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <Style id="houseIcon">
      <IconStyle>
        <scale>1.1</scale>
        <Icon>
          <href>http://www.pottononline.net/assets/map/icons/houseIcon.png</href>
        </Icon>
      </IconStyle>
    </Style>
    <Placemark>
      <name>This is a marker name</name>
      <description>Marker Description</description>
      <styleUrl>#houseIcon</styleUrl>
      <Point>
        <coordinates>-180.12345,0.12345</coordinates>
      </Point>
    </Placemark>
  </Document>
</kml>

"""

###############################
verbose = False

if verbose:  print "Loading Django models..."
from pottononline.map.models import Marker
from pottononline.map.models import MarkerType
from xml.sax.saxutils import escape



markers = Marker.objects.filter(active = True)
#icons = Icon.objects.all()
markertypes = MarkerType.objects.all()

output_file = open('pottononline.kml','w')

url_seed = u"http://www.pottononline.net/assets/map/icons/"

# Head for the XML/KML file
xml = u'<?xml version="1.0" encoding="UTF-8"?>\n\t<kml xmlns="http://www.opengis.net/kml/2.2">\n\t\t<Document>'

# Functions to escape strings for XML

def escape_xml(marker_string):
  if marker_string != None:
    return escape(marker_string)
  else:
    return "None"

if verbose:  print "Creating the xml Style nodes..."
# Set up the styles for the map icons
for markertype in markertypes:
  node = u'\n\t\t\t<Style id="%s">\n\t\t\t\t<IconStyle>\n\t\t\t\t\t<scale>1.1</scale>\n\t\t\t\t\t<Icon>\n\t\t\t\t\t\t<href>%s</href>\n\t\t\t\t\t</Icon>\n\t\t\t\t</IconStyle>\n\t\t\t</Style>' % (markertype.safename(),url_seed+markertype.icon.image)
  xml += node
  
# Write out the markers

for marker in markers:
  node = u'\n\t\t\t<Placemark>\n\t\t\t\t<name>%s</name>\n\t\t\t\t<description>%s</description>\n\t\t\t\t<styleUrl>#%s</styleUrl>' % (escape_xml(marker.name), escape_xml(marker.description), marker.itemtype.safename())
  node += u'\n\t\t\t\t<Point>\n\t\t\t\t\t<coordinates>%s</coordinates>\n\t\t\t\t</Point>\n\t\t\t</Placemark>' % (str(marker.lon)+','+str(marker.lat))
  xml += node

# Close the XML and the file
xml += u"\n\t\t</Document>\n\t</kml>\n" 

utf = xml.encode('utf-8')
output_file.write(utf)
output_file.close()

if verbose: print xml
